'''
Created on Dec 6, 2009

@author: bodnaria
'''
import os
import cgi
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.db import BadValueError
import appengine_utilities.sessions
from util import BBPage
import hashlib
from model.User import getUserByUsername, createUser
from error.UserError import UserError as UserError
from model.TempUser import getUserByKey, deleteKey


class CreateProfilePage(BBPage):
    def get(self):
        messages = {"badfields" : "Please fill out all fields properly."}        
        
        self.outputHeader()

        error = self.request.get("error")
        if not error in messages.keys():
            message = ""
        else:
            message = messages[error]

        template_values = {
            "error" : "",
            "key" : cgi.escape(self.request.get("key")),
        }

        templatePath = os.path.join(os.path.dirname(__file__), 'create_profile.html')
        self.response.out.write(template.render(templatePath, template_values)) 
    
    def post(self):
        name = cgi.escape(self.request.get("name"))
        gender = cgi.escape(self.request.get("gender"))
        age = int(cgi.escape(self.request.get("age")))
        city = cgi.escape(self.request.get("location"))
        desc = cgi.escape(self.request.get("desc"))
        link = cgi.escape(self.request.get("website"))
        password = cgi.escape(self.request.get("password"))
        password2 = cgi.escape(self.request.get("password2"))
        key = cgi.escape(self.request.get("key"))
        
        try:
            tuser = getUserByKey(key)
        except:
            self.redirect('/error')
            return
        
        if password != password2:
            raise ValueError()
        
        hashed_password = hashlib.sha256(password).hexdigest()
        
        try:
            user = createUser(tuser.username, hashed_password, tuser.email, 50.0, name, city, link, desc, gender, age)
            deleteKey(key)   
                           
        except Exception:
            self.redirect('/create_profile?error=badfields&key='+key)
            return 
        
        session = appengine_utilities.sessions.Session()
        session["username"] = user.username        
        self.redirect('/profile?user='+user.username)
        
        
